/*
 * Copyright 2002-2022 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.itclass.auth.authentication.filter;


import com.itclass.auth.authentication.adapter.AuthenticationAdapter;
import org.springframework.context.ApplicationContext;
import org.springframework.security.config.annotation.web.HttpSecurityBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractAuthenticationFilterConfigurer;
import org.springframework.security.web.authentication.ForwardAuthenticationFailureHandler;
import org.springframework.security.web.authentication.ForwardAuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


public final class CustomLoginConfigurer<H extends HttpSecurityBuilder<H>> extends
		AbstractAuthenticationFilterConfigurer<H, CustomLoginConfigurer<H>, LoginAuthenticationFilter> {

	/**
	 * Creates a new instance
	 * @see HttpSecurity#formLogin()
	 */
	public CustomLoginConfigurer() {
		super(new LoginAuthenticationFilter(), null);
		usernameParameter("username");
		passwordParameter("password");
	}


	@Override
	public CustomLoginConfigurer<H> loginPage(String loginPage) {
		return super.loginPage(loginPage);
	}

	public CustomLoginConfigurer<H> usernameParameter(String usernameParameter) {
		getAuthenticationFilter().setUsernameParameter(usernameParameter);
		return this;
	}

	public CustomLoginConfigurer<H> passwordParameter(String passwordParameter) {
		getAuthenticationFilter().setPasswordParameter(passwordParameter);
		return this;
	}

	public CustomLoginConfigurer<H> failureForwardUrl(String forwardUrl) {
		failureHandler(new ForwardAuthenticationFailureHandler(forwardUrl));
		return this;
	}

	public CustomLoginConfigurer<H> successForwardUrl(String forwardUrl) {
		successHandler(new ForwardAuthenticationSuccessHandler(forwardUrl));
		return this;
	}

	@Override
	public void init(H http) throws Exception {
		super.init(http);
		addFilterOrder(http);
		initDefaultLoginFilter(http);
		initAuthenticationAdapter(http);
		

	}


	/**
	 * 初始化认证令牌适配器 以及 初始化认证请求匹配器
	 * @param http
	 */
	private void initAuthenticationAdapter(H http) {
		ApplicationContext context = http.getSharedObject(ApplicationContext.class);

		List<AuthenticationAdapter> authenticationAdapterList = new ArrayList<>();
		for (String beanName : context.getBeanNamesForType(AuthenticationAdapter.class)) {
			AuthenticationAdapter bean = context.getBean(beanName, AuthenticationAdapter.class);
			authenticationAdapterList.add(bean);
		}
		this.getAuthenticationFilter().setAuthenticationAdapterList(authenticationAdapterList);
	}

	/**
	 * 添加自定义过滤器的顺序
	 * @param http
	 */
	private void addFilterOrder(H http) {
		Field filterOrdersField = ReflectionUtils.findField(http.getClass(), "filterOrders");
		filterOrdersField.setAccessible(true);
		Object filterOrderRegistration = ReflectionUtils.getField(filterOrdersField, http);
		Field filterToOrderMapField = ReflectionUtils.findField(filterOrderRegistration.getClass(), "filterToOrder");
		filterToOrderMapField.setAccessible(true);
		HashMap<String,Integer> filterToOrderMap = (HashMap<String, Integer>) ReflectionUtils.getField(filterToOrderMapField, filterOrderRegistration);
		Integer order = filterToOrderMap.get(UsernamePasswordAuthenticationFilter.class.getName());
		filterToOrderMap.put(LoginAuthenticationFilter.class.getName(),order+1);


	}
	@Override
	protected RequestMatcher createLoginProcessingUrlMatcher(String loginProcessingUrl) {

		return new AntPathRequestMatcher(loginProcessingUrl, "POST");
	}

	public void addRequestMatcher(RequestMatcher requestMatcher){
		this.getAuthenticationFilter().getRequestMatcherAdapter().addRequestMatchers(requestMatcher);
	}

	private String getUsernameParameter() {
		return getAuthenticationFilter().getUsernameParameter();
	}

	private String getPasswordParameter() {
		return getAuthenticationFilter().getPasswordParameter();
	}

	/**
	 * If available, initializes the {@link DefaultLoginPageGeneratingFilter} shared
	 * object.
	 * @param http the {@link HttpSecurityBuilder} to use
	 */
	private void initDefaultLoginFilter(H http) {
		DefaultLoginPageGeneratingFilter loginPageGeneratingFilter = http
				.getSharedObject(DefaultLoginPageGeneratingFilter.class);
		if (loginPageGeneratingFilter != null && !isCustomLoginPage()) {
			loginPageGeneratingFilter.setFormLoginEnabled(true);
			loginPageGeneratingFilter.setUsernameParameter(getUsernameParameter());
			loginPageGeneratingFilter.setPasswordParameter(getPasswordParameter());
			loginPageGeneratingFilter.setLoginPageUrl(getLoginPage());
			loginPageGeneratingFilter.setFailureUrl(getFailureUrl());
			loginPageGeneratingFilter.setAuthenticationUrl(getLoginProcessingUrl());
		}
	}
}
